<?php
namespace backend\models;

use Yii;
use yii\base\Model;
use yii\base\Exception;
use common\models\Customer;
use common\models\CustomerOrder;
use common\models\OrderProduct;
use common\models\TransferUndertake;

class ExecuteForm extends Model
{
    public $pcode;
    public $oid;
    public $pid;
    public $prepareid;
    public $transfer;
    public $undertake;
    public $send_code;
    public $send_time;
    public $delivery_code;
    public $sign_time;
    public $out_storage_time;
    public $price;

	public function formName()
    {
        return '';
    }

	public function rules()
	{
		return [
            [['pcode', 'oid', 'transfer', 'prepareid', 'pid'], 'required'],
            [['send_code', 'undertake', 'send_time', 'delivery_code', 'sign_time', 'out_storage_time', 'price'], 'safe']
		];
	}

    public function execute()
    {
        if ($this->pid == 'finish') {
            $complete_task = TransferUndertake::findOne($this->prepareid);
            $complete_task->status = TransferUndertake::DISABLE_STATUS;
            if ($complete_task->save(false)) {

                return true;
            } else {

                return false;
            }
        }

        $transfer_undertake = new TransferUndertake;
        $transfer_undertake->transfer = $this->transfer;
        $transfer_undertake->undertake = $this->undertake;
        $transfer_undertake->pid = $this->pid;
        $transfer_undertake->pcode = $this->pcode;
        $transfer_undertake->oid = $this->oid;
        $transfer_undertake->status = TransferUndertake::ACTIVE_STATUS;
        $order_product = OrderProduct::find()->where(['oid' => $this->oid])->one();
        if ($this->send_code) {
            $order_product->send_code = $this->send_code;
        }
        if ($this->send_time) {
            $order_product->send_time = strtotime($this->send_time);
        }
        if ($this->delivery_code) {
            $order_product->delivery_code = $this->delivery_code;
        }
        if ($this->sign_time) {
            $order_product->sign_time = strtotime($this->sign_time);
        }
        if ($this->out_storage_time) {
            $order_product->out_storage_time = strtotime($this->out_storage_time);
        }
        if ($this->price) {
            $order_product->price = trim($this->price);
        }
        $complete_task = TransferUndertake::findOne($this->prepareid);
        $complete_task->status = TransferUndertake::DISABLE_STATUS;

        if (TransferUndertake::getDb()->transaction(function($db) use ($transfer_undertake, $complete_task, $order_product) {
            
            return $transfer_undertake->save(false) && $complete_task->save(false) && $order_product->save(false);
        })) {

            return true;
        } else {

            return false;
        }
    }


}

